package com.example.gymmanagement.service.impl;

import com.example.gymmanagement.Utils.JWTUtils;
import com.example.gymmanagement.Utils.Result;
import com.example.gymmanagement.Utils.StatusCode;
import com.example.gymmanagement.domain.LoginParam;
import com.example.gymmanagement.domain.User;
import com.example.gymmanagement.service.LoginService;
import com.example.gymmanagement.service.UserService;
import io.micrometer.common.util.StringUtils;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;



    @Override
    public Result login(LoginParam loginParam) {
        long userId = loginParam.getUserId();
        String userpassword = loginParam.getUserPassword();
        System.out.println("eeeeee:"+userId+userpassword);
        //检查参数是否合法
        if (StringUtils.isBlank(String.valueOf(userId))|| StringUtils.isBlank(userpassword)){
            return new Result(StatusCode.LOGIN_ERR,"参数不合法");
        }
        //根据用户id和密码查询是否存在
        User user1 = this.userService.findUser(userId,userpassword);
        //不存在登录失败
        if (user1==null){
            return new Result(StatusCode.GET_ERR,"用户名不存在或密码错误");
        }
        // 存在则使用jwt生成token
        String token = JWTUtils.createToken(user1.getUserNum());
        //将token放入redis中，redis   token:user信息，设置过期时间1填
        redisTemplate.opsForValue().set("TOKEN_"+token, JSON.toJSONString(user1),30, TimeUnit.DAYS);
        //token返回给前端
        return new Result(StatusCode.LOGIN_OK,user1,token,"登录成功");
    }


    // （登录认证的时候，先认证token是否合法，再去redis验证是否存在）
     @Override
     public User checkToken(String token) {
        //验证token是否合法
         if (token ==null||token==""){
             return null;
         }
         //解析token
         Map<String,Object> stringObjectMap = JWTUtils.checkToken(token);
         if (stringObjectMap == null){
             return null;
         }
         //解析成功，在redis再次验证
         String userJson = redisTemplate.opsForValue().get("TOKEN_"+token);
         if(userJson == null || userJson==""){
             return null;
         }
         User user = JSON.parseObject(userJson,User.class);
         return user;
     }
    @Override
    public Result logout(String token) {
//        //删除redis中保存的token
//        if (token ==null||token==""||!redisTemplate.hasKey("TOKEN_"+token)){
//            return new Result(StatusCode.GET_ERR,"token不合法");
//        }
        //删除所有token
        Set<String> keys = redisTemplate.keys("*");
        redisTemplate.delete(keys);
        return new Result(StatusCode.GET_OK,"退出登录成功");
    }

    @Override
    public Result register(User user) {
        // 参数是否合法
        //账户是否存在
        if(user.getUserNum()==null||user.getUserPassword()==null){
            return new Result(StatusCode.LOGIN_ERR,"账号或密码不能为空");
        }
        User user1 = userService.selectById((user.getUserNum()).intValue());
        if (user1!= null){
            return new Result(StatusCode.LOGIN_ERR,"账号已被注册");
        }
        //账户不存在，注册用户
        boolean flag =false;
        String msg = "";
        try {
            flag = this.userService.insert(user);
            msg = flag?"注册成功":"注册失败";
        }catch (Exception e){
            return new Result(flag?StatusCode.SAVE_OK:StatusCode.SAVE_ERR,flag,"注册失败");
        }
            return new Result(flag?StatusCode.SAVE_OK:StatusCode.SAVE_ERR,flag,msg);
    }
}
